import React, { useEffect, useRef, useState } from "react";
import {
  Form,
  Button,
  Input,
  Table,
  Tag,
  Tooltip,
  Empty,
  message,
  Typography,
  Affix,
} from "antd";
import type { TableProps, TableColumnType } from "antd";
import styles from "./styles.module.less";
import EditableCell from "./editable";
import { Icon } from "@iconify-icon/react";
import { useMainStore } from "@/store/mainStore";
import { useShallow } from "zustand/react/shallow";
import {
  ExportCharacterCoordList,
  ImportCharacterCoordList,
  WriteCharacterCoord,
} from "@go/app/App";
import HotkeyModal from "./hotkeyModal";
import { RegisterHotkey, UnregisterHotkey } from "@go/app/HotkeyApp";
import { EventsOn } from "@runtime";

interface EditableColumnType extends TableColumnType<DataType> {
  /** 是否可编辑 */
  editable?: boolean;
}

const TableContent = () => {
  const [form] = Form.useForm();
  const [selectKeys, setSelectKeys] = useState<number[]>([]);
  const [editingKey, setEditingKey] = useState(0); // 编辑的key
  const coordListRef = useRef<DataType[]>([]);

  const { coordList, isLogin, currentHwnd, hotkeyModalInfo, cordTableLoading } =
    useMainStore(
      useShallow((state) => ({
        coordList: state.coordList,
        isLogin: state.isLogin,
        currentHwnd: state.currentHwnd,
        hotkeyModalInfo: state.hotkeyModalInfo,
        cordTableLoading: state.cordTableLoading,
      }))
    );

  // console.log("selectKeys", selectKeys);

  const isEditing = (record: DataType) => record.id === editingKey;

  // 编辑
  const edit = (record: Partial<DataType> & { id: number }) => {
    form.setFieldsValue({ name: "", age: "", address: "", ...record });
    setEditingKey(record.id);
  };

  // 取消
  const cancel = () => {
    setEditingKey(0);
  };

  // 保存
  const save = async (id: number) => {
    try {
      const row = (await form.validateFields()) as DataType;

      const newData = [...coordList];
      const index = newData.findIndex((item) => id === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        useMainStore.setState({ coordList: newData });
        setEditingKey(0);
      } else {
        newData.push(row);
        useMainStore.setState({ coordList: newData });
        setEditingKey(0);
      }
      message.success("编辑成功");
    } catch (errInfo) {
      message.error("编辑失败:" + errInfo);
    }
  };

  const rowSelection: TableProps<DataType>["rowSelection"] = {
    selectedRowKeys: selectKeys,
    onChange: (ids: any) => {
      setSelectKeys(ids);
    },
    getCheckboxProps: (record: DataType) => ({
      // 禁用条件
      // disabled: record.state === 1,
      // name: record.name,
    }),
  };

  // 删除
  const handleDelete = (ids: number[]) => {
    if (editingKey && ids.includes(editingKey)) {
      setEditingKey(0);
    }
    const newData = coordList.filter((item) => !ids.includes(item.id));
    useMainStore.setState({ coordList: newData });
    setSelectKeys(selectKeys.filter((id) => !ids.includes(id)));
    message.success("删除成功");
    ids.forEach((id) => {
      UnregisterHotkey(id);
    });
  };

  // 导入
  const handleImport = async () => {
    useMainStore.setState({ cordTableLoading: true });
    try {
      const resJson = await ImportCharacterCoordList();
      if (resJson == "") {
        // message.warning("已取消");
        return;
      }
      // 先遍历旧的热键，注销掉
      coordList.forEach((item) => {
        if (item.hotkey) {
          UnregisterHotkey(item.id);
        }
      });
      const list = JSON.parse(resJson || "[]");
      useMainStore.setState({ coordList: list });
      // 注册热键
      const hotkeyData = list.filter((item: any) => item.hotkey);
      hotkeyData.forEach((item: any) => {
        RegisterHotkey(item.hotkey, item.id);
      });
      hotkeyData.length > 0
        ? message.success(`导入成功,并注册${hotkeyData.length}个热键`)
        : message.success("导入成功");
    } catch (error) {
      console.log("error", error);
      message.error(`导入失败: 数据格式错误${error}`);
    } finally {
      useMainStore.setState({ cordTableLoading: false });
    }
  };

  // 导出
  const handleExport = async () => {
    try {
      const coordListJson = JSON.stringify(coordList, null, 2);
      const res = await ExportCharacterCoordList(coordListJson);
      if (res == "") {
        message.success("导出成功");
      } else if (res != "已取消") {
        message.error(`导出失败: ${res}`);
      }
    } catch (error) {
      message.error(`导出失败: ${error}`);
    }
  };

  const openHotkeyModal = (hotkey: string, id: number) => {
    useMainStore.setState({
      hotkeyModalVisible: true,
      hotkeyModalInfo: { id, hotkey },
    });
  };

  const columns: EditableColumnType[] = [
    {
      title: "x坐标",
      dataIndex: "x_coord",
      editable: true,
    },
    {
      title: "y坐标",
      dataIndex: "y_coord",
      editable: true,
    },
    {
      title: "z坐标",
      dataIndex: "z_coord",
      editable: true,
    },
    {
      title: "备注",
      dataIndex: "desc",
      editable: true,
      ellipsis: {
        showTitle: false,
      },
      render: (desc, record) => (
        <>
          <Tooltip placement="topLeft" title={desc}>
            {desc}
          </Tooltip>
          <br />
          {record.hotkey && (
            <Typography.Text
              style={{ fontSize: "12px" }}
              keyboard
              ellipsis={{
                tooltip: {
                  title: record.hotkey,
                  color: "#2db7f5",
                  placement: "topLeft",
                },
              }}
            >
              {record.hotkey}
            </Typography.Text>
          )}
        </>
      ),
    },
    {
      title: "操作",
      key: "operate",
      render: (_, record) => {
        const editable = isEditing(record);
        return (
          <div className={styles.operateBtn}>
            {editable ? (
              <div>
                <Button
                  color="primary"
                  variant="link"
                  onClick={() => save(record.id)}
                >
                  保存
                </Button>
                <Button color="primary" variant="link" onClick={cancel}>
                  取消
                </Button>
              </div>
            ) : (
              <div>
                <Button
                  color="primary"
                  variant="link"
                  disabled={!currentHwnd}
                  onClick={async () => {
                    const res = await WriteCharacterCoord(
                      currentHwnd as number,
                      record.x_coord,
                      record.y_coord,
                      record.z_coord
                    );
                    res && message.success("应用成功");
                  }}
                >
                  应用
                </Button>
                <Button
                  color="primary"
                  variant="link"
                  disabled={editingKey !== 0}
                  onClick={() => edit(record)}
                >
                  编辑
                </Button>
                <Button
                  color="primary"
                  variant="link"
                  onClick={() => {
                    openHotkeyModal(record.hotkey, record.id);
                  }}
                >
                  热键
                </Button>
                <Button
                  color="danger"
                  variant="link"
                  onClick={() => {
                    handleDelete([record.id]);
                  }}
                >
                  删除
                </Button>
              </div>
            )}
          </div>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        inputType: ["x_coord", "y_coord", "z_coord"].includes(
          col.dataIndex as string
        )
          ? "number"
          : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  useEffect(() => {
    EventsOn("writeCoord", async (id: number) => {
      const coord = coordListRef.current.find((item) => item.id === id);
      if (!coord) {
        return;
      }
      const res = await WriteCharacterCoord(
        0,
        coord.x_coord,
        coord.y_coord,
        coord.z_coord
      );
      res && message.success("应用成功");
    });
  }, []);

  useEffect(() => {
    coordListRef.current = coordList;
  }, [coordList]);

  return (
    <Form form={form} component={false}>
      <div className={styles.tableToolsBtn}>
        <div>
          <Button
            color="danger"
            variant="outlined"
            size="small"
            disabled={selectKeys.length === 0}
            onClick={() => {
              handleDelete(selectKeys);
            }}
          >
            批量删除
          </Button>
        </div>
        <div>
          <Button
            color="primary"
            variant="outlined"
            size="small"
            // clarity:import-line
            icon={<Icon icon="iconoir:import" />}
            iconPosition="end"
            onClick={handleImport}
          >
            导入
          </Button>
          <Button
            color="primary"
            variant="outlined"
            size="small"
            icon={<Icon icon="ph:export" />}
            iconPosition="end"
            onClick={handleExport}
          >
            导出
          </Button>
        </div>
      </div>
      <Table
        components={{
          body: { cell: EditableCell },
        }}
        style={{ padding: "10px 0", flex: 1 }}
        bordered
        size="middle"
        loading={cordTableLoading}
        rowKey="id"
        columns={mergedColumns as TableProps<DataType>["columns"]}
        dataSource={coordList}
        pagination={false}
        sticky={{ offsetHeader: 0 }}
        rowSelection={{ type: "checkbox", ...rowSelection }}
        locale={{
          emptyText: <Empty description="暂无坐标数据，快添加一条吧"></Empty>,
        }}
        onRow={(record) => ({
          style: {
            backgroundColor: record.hotkey ? "#e6f7ff" : "",
          },
        })}
      />
      <HotkeyModal
        onOk={(hotkey: string) => {
          // 将热键写入到当前行
          const newData = [...coordList];
          const index = newData.findIndex(
            (item) => item.id === hotkeyModalInfo.id
          );
          if (index > -1) {
            const item = newData[index];
            newData.splice(index, 1, {
              ...item,
              hotkey,
            });
            useMainStore.setState({ coordList: newData });
          }
          if (hotkey) {
            RegisterHotkey(hotkey, hotkeyModalInfo.id);
            message.success("热键注册成功");
          } else {
            UnregisterHotkey(hotkeyModalInfo.id);
            message.success("热键注销成功");
          }
        }}
      />
    </Form>
  );
};

export default TableContent;
